import React, {Component} from 'react';
import "./index.css"
// 创建Context上下文对象
const myContext = React.createContext()
const {Provider,Consumer} = myContext

class A extends Component {
    state = {
        username: '张三',
        age: 18
    }

    render() {
        const {username, age} = this.state

        return (
            <div className="parent">
                <h2>我是A组件</h2>
                <h3>我的用户名是:{username},年龄是{age}</h3>
                <Provider value={{username, age}}>
                    <B/>
                </Provider>

            </div>
        );
    }
}

class B extends Component {
    static contextType = myContext

    render() {
        console.log('B收到的context', this.context)
        return (
            <div className="child">
                <h2>我是B组件</h2>
                <h3>我从A接收的用户名是:{this.props.username},年龄是{this.props.age}</h3>
                <C/>
            </div>
        );
    }
}

// class C extends Component {
// 声明接收context
//     static contextType = myContext
//     render() {
//
//
//         const {username,age} = this.context
//         return (
//             <div className="grand">
//                <h2>我是C组件</h2>
//                 <h3>我从A接收的用户名是:{username},年龄是{age}</h3>
//             </div>
//         );
//     }
// }

function C() {
    return (
        <div className="grand">
            <h2>我是C组件</h2>
            <h3>我从A接收的用户名是
                {/*使用Consumer的方式无论是类式组件还是函数组件都是可以接收得到参数*/}
                <Consumer>
                    {
                        value => `${value.username},年龄是${value.age}`
                    }
                </Consumer>
            </h3>
        </div>
    )
}


export default A;
